package com.lobaby.tools.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Administrator
 *         Created by Administrator on 2019/11/25 0025.
 */
public class StringUtil {
    private final static org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(StringUtil.class);

    public static String getCurrentJarPath(Class<? extends Object> clazz) {
        String path = clazz.getProtectionDomain().getCodeSource().getLocation().getPath();
        path = path.substring(1);
        return path.substring(0, path.lastIndexOf("/"));
    }

    public static File getCurrentJarPathFile(Class<? extends Object> clazz, String pathSuffix) {
        String path = getCurrentJarPath(clazz);
        LOGGER.info("===============> jarPath: " + path);

        File resoureDir = new File(path + pathSuffix);
        if (!resoureDir.exists()) {
            resoureDir.mkdirs();
        }
        return resoureDir;
    }

    public static int parseInt(String str) {
        String regEx="[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        String result = m.replaceAll("").trim();
        if (isBlank(result)) {
            return 0;
        } else {
            return Integer.parseInt(result);
        }
    }

    public static String getFileName(File file) {
        if (file == null) {
            return "";
        }

        String filename = file.getName();
        return getFileName(filename);
    }

    public static String getFileName(String filename) {
        if (isBlank(filename)) {
            return "";
        }

        return filename.substring(0, filename.lastIndexOf("."));
    }

    public static String getFileType(File file) {
        if (file == null) {
            return "";
        }

        return getFileType(file.getName());
    }

    public static String getFileType(String filename) {
        if (isBlank(filename)) {
            return "";
        }
        return filename.substring(filename.lastIndexOf(".") + 1);
    }

    public static boolean equals(String string1, String string2) {
        if (string1 == string2) {
            return true;
        } else {
            if ((string1.equals("") && string2 == null ) || (string2.equals("") && string1 == null )) {
                return true;
            } else {
                return string1.equals(string2);
            }
        }
    }

    public static String substrings(String string, String instr) {
        if (string == null) {
            return "";
        }

        if (string.indexOf(instr) == -1) {
            return "";
        }

        return string.substring(0, string.indexOf(instr)) + string.substring(string.indexOf(instr) + instr.length(), string.length());
    }

    public static String getRegexpstr(String string) {
        return "^" + string + "$|^" + string + ",.*|.*," + string + ",.*|.*," + string + "$|^" + string + ":.*|.*," + string + ":.*";
    }

    /**
     * 合并数组
     *
     * @param arrays
     * @return
     */
    public static String[] concatArrays(String[] ...arrays) {
        if (arrays.length <= 0) {
            return null;
        }

        List<String> list = new ArrayList<>();
        for (int i = 0; i < arrays.length; i++) {
            for (int j = 0; j < arrays[i].length; j++) {
                list.add(arrays[i][j]);
            }
        }
        String[] strings = {};
        return list.toArray(strings);
    }

    /**
     * 对前台返回的数据进行解码操作
     *
     * @param map
     * @return
     */
    public static Map<String, String> getParams(Map<String, String> map)
    {
        if (map == null)
        {
            return new HashMap<>();
        }

        String encode = map.get("encode");
        if (isBlank(encode))
        {
            return map;
        }
        else
        {
            if (encode.indexOf(",") != -1)
            {
                Arrays.asList(encode.split(",")).stream().forEach(x -> {
                    String key = x.trim();
                    if (!isBlank(map.get(key)))
                    {
                        try
                        {
                            String value = URLDecoder.decode(map.get(key), "UTF-8");
                            map.put(key, value);
                        }
                        catch (Exception e)
                        {
                            LOGGER.error("",e);
                        }
                    }
                    else
                    {
                        if (key.indexOf(".") != -1)
                        {
                            String objName = key.split("\\.")[0];
                            String fieldName = key.split("\\.")[1];
                            Object parse = JSONObject.parse(map.get(objName));

                            if (parse instanceof JSONObject)
                            {
                                JSONObject object = (JSONObject) parse;
                                String value = (String) object.get(fieldName);
                                if (!isBlank(value))
                                {
                                    try
                                    {
                                        object.put(fieldName, URLDecoder.decode(value, "UTF-8"));
                                        map.put(objName, object.toString());
                                    }
                                    catch (Exception e)
                                    {
                                        LOGGER.error("",e);
                                    }
                                }
                            }
                            else if (parse instanceof JSONArray)
                            {
                                JSONArray array = (JSONArray) parse;
                                JSONArray resultArray = new JSONArray();
                                for (int i = 0; i < array.size(); i++)
                                {
                                    JSONObject object = (JSONObject) array.get(i);
                                    String value = (String) object.get(fieldName);
                                    if (value != null)
                                    {
                                        try
                                        {
                                            object.put(fieldName, URLDecoder.decode(value, "UTF-8"));
                                            resultArray.add(object);
                                        }
                                        catch (Exception e)
                                        {
                                            LOGGER.error("",e);
                                        }
                                    }
                                }
                                map.put(objName, resultArray.toString());
                            }
                            else
                            {

                            }
                        }
                    }
                });
            }
            else
            {
                try
                {
                    if (StringUtil.isBlank(map.get(encode.trim()))) {
                        map.put(encode, "");
                    } else {
                        String value = URLDecoder.decode(map.get(encode.trim()), "UTF-8");
                        map.put(encode, value);
                    }
                }
                catch (Exception e)
                {
                    LOGGER.error("",e);
                }
            }
        }

        return map;
    }

    public static float getFloat(float value, int bouns)
    {
        int roundingMode = 4;// 表示四舍五入，可以选择其他舍值方式，例如去尾，等等.
        BigDecimal bd = new BigDecimal((double) value);
        bd = bd.setScale(bouns, roundingMode);
        return bd.floatValue();
    }

    /**
     * string encoding by: new String(s.getBytes("iso-8859-1"), "utf-8");
     *
     * @param str
     *        str to be encoding
     * @return result
     */
    public static String getUTF8String(String str)
    {
        if (str == null)
        {
            return null;
        }
        if (str.equals(""))
        {
            return "";
        }

        try
        {
            return new String(str.getBytes("iso-8859-1"), "utf-8");
        }
        catch (UnsupportedEncodingException e)
        {
            throw new IllegalArgumentException("unknown encoding");
        }
    }

    public static boolean isBlank(String str)
    {
        if (str == null || str.equals(""))
        {
            return true;
        }
        return false;
    }

    /**
     * 判断字符串是否为null 或 去除前后空格后 为""
     *
     * @param str
     * @return
     */
    public static boolean isNotValid(String str)
    {
        return str == null || str.trim().length() == 0;
    }

    /**
     * 获取指定长度的随机数字
     *
     * @param length
     * @return
     */
    public static String getRandomNumber(int length)
    {
        String result = "";
        String[] arr = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
        Random r = new Random();
        for (int i = 0; i < length; i++)
        {
            result += arr[r.nextInt(arr.length)];
        }

        return result;
    }

    public static String getRandomString(int length)
    {
        String s = "qwertyupsadfghjklxzcvbnmQWERTYUPASDFGHJKLZXCVBNM23456789_-";
        StringBuffer buffer = new StringBuffer();
        Random r = new Random();
        for (int i = 0; i < length; i++)
        {
            int i2 = r.nextInt(s.length());
            buffer.append(s.charAt(i2));
        }
        return buffer.toString();
    }

    /**
     * 数字左侧补零
     *
     * @param str
     * @param length
     * @return
     */
    public static String addZeroLeft(String str, int length)
    {
        return addStringLeft(str, length, '0');
    }

    public static String addBlankRight(String str, int length) {
        if (str == null)
        {
            str = "";
        }
        StringBuilder zeros = new StringBuilder();
        zeros.append(str);
        for (int i = 0; i < length - str.length(); i++)
        {
            zeros.append(" ");
        }
        return zeros.toString();
    }

    /**
     * 数字左侧补空格
     *
     * @param str
     * @param length
     * @return
     */
    public static String addBlankLeft(String str, int length)
    {
        return addStringLeft(str, length, ' ');
    }

    /**
     * 字符串左侧补空格
     *
     * @param str
     * @param length
     * @param c 填充字符
     * @return
     */
    public static String addStringLeft(String str, int length, char c)
    {
        if (str == null)
        {
            str = "";
        }
        StringBuilder zeros = new StringBuilder();
        for (int i = 0; i < length - str.length(); i++)
        {
            zeros.append(c);
        }
        zeros.append(str);
        return zeros.toString();
    }

    /**
     * 解决EXCEL导出时文件名乱码问题
     *
     * @param s
     * @return
     */
    public static String toUtf8String(String s)
    {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++)
        {
            char c = s.charAt(i);
            if (c >= 0 && c <= 255)
            {
                sb.append(c);
            }
            else
            {
                byte[] b;
                try
                {
                    b = Character.toString(c).getBytes("utf-8");
                }
                catch (Exception ex)
                {
                    LOGGER.debug(""+ex);
                    b = new byte[0];
                }
                for (int j = 0; j < b.length; j++)
                {
                    int k = b[j];
                    if (k < 0)
                        k += 256;
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }

    public static String hexStrToBinStr(String hexStr)
    {
        if (hexStr != null)
        {
            String temp = hexStr.toUpperCase();
            String binStr = "";
            for (int i = 0; i < temp.length(); i++)
            {
                char ch = temp.charAt(i);
                switch (ch)
                {
                    case '0':
                        binStr += "0000";
                        break;
                    case '1':
                        binStr += "0001";
                        break;
                    case '2':
                        binStr += "0010";
                        break;
                    case '3':
                        binStr += "0011";
                        break;
                    case '4':
                        binStr += "0100";
                        break;
                    case '5':
                        binStr += "0101";
                        break;
                    case '6':
                        binStr += "0110";
                        break;
                    case '7':
                        binStr += "0111";
                        break;
                    case '8':
                        binStr += "1000";
                        break;
                    case '9':
                        binStr += "1001";
                        break;
                    case 'A':
                        binStr += "1010";
                        break;
                    case 'B':
                        binStr += "1011";
                        break;
                    case 'C':
                        binStr += "1100";
                        break;
                    case 'D':
                        binStr += "1101";
                        break;
                    case 'E':
                        binStr += "1110";
                        break;
                    case 'F':
                        binStr += "1111";
                        break;
                }
            }
            return binStr;
        }
        return "";
    }

    public static String binStrToHexStr(String binStr)
    {
        String hexStr = "";
        for (int i = 0; i < binStr.length(); i += 4)
        {
            hexStr += Integer.toHexString(Integer.parseInt(binStr.substring(i, i + 4), 2)).toUpperCase();
        }
        return hexStr;
    }

    /**
     * 将金额转换成分,去掉小数点
     *
     * @param money
     * @return
     */
    public static String getStringMoneys(String money)
    {

        if ((money != null) && (!money.equals("")))
        {
            if (money.indexOf('.') == -1)
            {
                money = money + "00";
            }
            else if (money.substring(money.indexOf('.') + 1, money.length()).length() == 1)
            {
                money = money.substring(0, money.indexOf('.'))
                        + money.substring(money.indexOf('.') + 1, money.indexOf('.') + 2);
                money = money + "0";
            }
            else
            {
                money = money.substring(0, money.indexOf('.'))
                        + money.substring(money.indexOf('.') + 1, money.indexOf('.') + 3);
            }
        }
        return money;
    }

    /**
     * 数组转换字符串
     *
     * @param ts
     * @return
     */
    public static <T> String arrayToString(T[] ts)
    {
        return ts == null ? "null" : Arrays.toString(ts);
    }

    /**
     * 删除起始字符
     *
     * @param str
     * @param trim 字符
     * @return
     */
    public static String trimStart(String str, String trim)
    {
        if (str == null)
            return null;
        return str.replaceAll("^(" + trim + ")+", "");
    }

    /**
     * 删除末尾字符
     *
     * @param str
     * @param trim 字符
     * @return
     */
    public static String trimEnd(String str, String trim)
    {
        if (str == null)
            return null;
        return str.replaceAll("(" + trim + ")+$", "");
    }

    /**
     * 解析文件
     *
     * @param filePath 文件路径
     * @return
     */
    public static ArrayList<File> fileToStringList(String filePath)
    {
        // 目标集合fileList
        ArrayList<File> fileList = new ArrayList<File>();
        File file = new File(filePath);
        if (file.isDirectory())
        {
            File[] files = file.listFiles();
            for (File fileIndex : files)
            {
                if (fileIndex.isDirectory())
                {
                    fileToStringList(fileIndex.getPath());
                }
                else
                {
                    fileList.add(fileIndex);
                }
            }
        }
        return fileList;
    }

    public static String null2Empty(String str)
    {
        return StringUtil.isBlank(str) ? "" : str;
    }

    /**
     * 去掉首尾空格
     *
     * @param param
     * @return
     */
    public static String removeTrim(String param)
    {
        if (param == null)
        {
            return "";
        }
        return param.trim();
    }

}
